package com.pureut.quality.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.quality.domain.QualityInspectionDocument;
import com.pureut.quality.domain.QualitySchemeConfiguration;
import com.pureut.quality.domain.QualityTemporary;
import com.pureut.quality.domain.dto.MaterialQualityDto;
import com.pureut.quality.domain.dto.QualityTemporaryDto;
import com.pureut.quality.domain.vo.QualitySchemeConfigurationVo;
import com.pureut.quality.domain.vo.QualityTemporaryVo;
import com.pureut.quality.mapper.QualityInspectionDocumentMapper;
import com.pureut.quality.mapper.QualitySchemeConfigurationMapper;
import com.pureut.quality.mapper.QualityTemporaryMapper;
import com.pureut.quality.service.QualitySchemeConfigurationService;
import com.pureut.quality.service.QualityTemporaryService;
import com.pureut.system.api.domain.SysDictData;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/***
 *
 * Author:C
 * Date:2023/02/06 15:24
 * @DESC
 */
@Service
public class QualityTemporaryServiceImpl extends ServiceImpl<QualityTemporaryMapper, QualityTemporary> implements QualityTemporaryService {


    @Resource
    QualityTemporaryMapper qualityTemporaryMapper;

    @Resource
    QualityInspectionDocumentMapper qualityInspectionDocumentMapper;

    @Resource
    QualitySchemeConfigurationMapper qualitySchemeConfigurationMapper;

    @Resource
    QualitySchemeConfigurationService qualitySchemeConfigurationService;


    /**
     * 根据检验单号获取物料号码
     *
     * @param inspectionSheetNo
     * @return
     */
    @Override
    public List<QualityTemporaryDto> getMaterialNumber(String inspectionSheetNo, String batchNo) {
        QualityInspectionDocument qualityInspectionDocument = qualityInspectionDocumentMapper.selectOne(new QueryWrapper<QualityInspectionDocument>().lambda().eq(QualityInspectionDocument::getInspectionSheetNo, inspectionSheetNo));
        if (qualityInspectionDocument.getBatchNo() != null) {
            List<String> batchNoList = Arrays.asList(qualityInspectionDocument.getBatchNo().split(","));
            return qualityTemporaryMapper.getMaterialNumber(inspectionSheetNo, batchNoList);
        } else {
            throw new GlobalException("该物料批次号为空，请核实!");
        }
    }

    /**
     * 获取条数(检验进度总条数)
     *
     * @param qualitySchemeConfigurationVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int getTotalSize(QualitySchemeConfigurationVo qualitySchemeConfigurationVo) {
        //根据阶别、类别、方案类型、物料编码查询检验配置
        Long byCodeIds = qualitySchemeConfigurationMapper.getConfigurationListByCode(qualitySchemeConfigurationVo);
        //先获取该检验单下物料的总条数
        List<QualityTemporary> list = list(new QueryWrapper<QualityTemporary>().lambda().eq(QualityTemporary::getInspectionSheetNo, qualitySchemeConfigurationVo.getInspectionSheetNo()));
        if (byCodeIds != null) {
            //获取该方案下的抽样方式，抽样量，返回检验进度总条数
            QualitySchemeConfiguration byId = qualitySchemeConfigurationService.getById(byCodeIds);
            if (byId.getSamplingMethod() == 1) {
                //固定值
                if ((int) byId.getSamplingNum() > list.size()) {
                    return list.size();
                } else {
                    return (int) byId.getSamplingNum();
                }
            } else {
                //范围值
                BigDecimal multiply = new BigDecimal(list.size()).multiply(new BigDecimal(byId.getSamplingNum()));
                BigDecimal divide = multiply.divide(new BigDecimal(100), RoundingMode.UP);
                return Integer.parseInt(divide.toString());
            }
        } else {
            //根据阶别、类别、方案类型、物料类别查询检验项目
            Long byCategoryIds = qualitySchemeConfigurationMapper.getConfigurationListByCategory(qualitySchemeConfigurationVo);
            //获取该方案下的抽样方式，抽样量，返回检验进度总条数
            if (byCategoryIds != null) {
                QualitySchemeConfiguration byId = qualitySchemeConfigurationService.getById(byCategoryIds);
                if (byId.getSamplingMethod() == 1) {
                    //固定值
                    if ((int) byId.getSamplingNum() > list.size()) {
                        return list.size();
                    } else {
                        return (int) byId.getSamplingNum();
                    }
                } else {
                    //范围值
                    BigDecimal multiply = new BigDecimal(list.size()).multiply(new BigDecimal(byId.getSamplingNum()));
                    BigDecimal divide = multiply.divide(new BigDecimal(100), RoundingMode.UP);
                    return Integer.parseInt(divide.toString());
                }
            }else {
                throw new GlobalException("没有获取相关检验配置");
            }
        }
//        return 0;
    }

    /**
     * 获取列表
     *
     * @param inspectionSheetNo
     * @return
     */
    @Override
    public List<QualityTemporaryDto> getList(String inspectionSheetNo) {

        //检验结果
        List<SysDictData> resultsArray = DictUtils.getDictCache("quality_inspection_results");
        Map<String, String> resultsMap = resultsArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        List<QualityTemporaryDto> list = qualityTemporaryMapper.getList(inspectionSheetNo);
        for (QualityTemporaryDto entry : list) {
            entry.setInspectionResultsDict(resultsMap.get(entry.getInspectionResults()));
        }
        return list;
    }

    /**
     * 物料新增接口（feign调用）
     *
     * @param qualityTemporaryVo
     * @return
     */
    @Override
    public boolean materialAdd(QualityTemporaryVo qualityTemporaryVo) {

        QualityTemporary qualityTemporary = new QualityTemporary();
        qualityTemporary.setMaterialNumber(qualityTemporaryVo.getMaterialNumber());
        qualityTemporary.setInspectionSheetNo(qualityTemporaryVo.getInspectionSheetNo());
        qualityTemporary.setMaterialCode(qualityTemporaryVo.getMaterialCode());
        qualityTemporary.setInspectionMark(2);
        return save(qualityTemporary);
    }

    /**
     * 查询品检信息（feign调用 追溯管理页面使用）
     *
     * @param wsiMaterialNumber 根据物料号码查询关联的品质检验单
     * @return
     */
    @Override
    public List<MaterialQualityDto> getQualityTemporaryList(String wsiMaterialNumber) {
        // 检验阶别
        List<SysDictData> itemRank = DictUtils.getDictCache("item_rank");
        Map<String, String> itemRankMap = itemRank.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        // 检验结果
        List<SysDictData> qualityInspectionResults = DictUtils.getDictCache("quality_inspection_results");
        Map<String, String> qualityInspectionResultsMap = qualityInspectionResults.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        // 判定等级
        List<SysDictData> qualityJudgmentGrade = DictUtils.getDictCache("quality_judgment_grade");
        Map<String, String> qualityJudgmentGradeMap = qualityJudgmentGrade.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        List<MaterialQualityDto> list = qualityTemporaryMapper.getQualityTemporaryList(wsiMaterialNumber);

        for (MaterialQualityDto materialQualityDto : list) {
            materialQualityDto.setItemRankDict(itemRankMap.get(materialQualityDto.getItemRank()));
            materialQualityDto.setInspectionResultsDict(qualityInspectionResultsMap.get(materialQualityDto.getInspectionResults()));
            materialQualityDto.setJudgmentGradeDict(qualityJudgmentGradeMap.get(materialQualityDto.getJudgmentGrade()));
        }
        return list;
    }

    /**
     * 查询巡检信息（feign调用 追溯管理页面使用）
     *
     * @param wsiMaterialNumber 根据物料号码查询关联的巡检单
     * @return
     */
    @Override
    public List<MaterialQualityDto> getPatrolTemporaryList(String wsiMaterialNumber) {
        // 检验阶别
        List<SysDictData> itemRank = DictUtils.getDictCache("item_rank");
        Map<String, String> itemRankMap = itemRank.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        // 检验结果
        List<SysDictData> qualityInspectionResults = DictUtils.getDictCache("quality_inspection_results");
        Map<String, String> qualityInspectionResultsMap = qualityInspectionResults.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        // 判定等级
        List<SysDictData> qualityJudgmentGrade = DictUtils.getDictCache("quality_judgment_grade");
        Map<String, String> qualityJudgmentGradeMap = qualityJudgmentGrade.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        List<MaterialQualityDto> list = qualityTemporaryMapper.getPatrolTemporaryList(wsiMaterialNumber);

        for (MaterialQualityDto materialQualityDto : list) {
            materialQualityDto.setItemRankDict(itemRankMap.get(materialQualityDto.getItemRank()));
            materialQualityDto.setInspectionResultsDict(qualityInspectionResultsMap.get(materialQualityDto.getInspectionResults()));
            materialQualityDto.setJudgmentGradeDict(qualityJudgmentGradeMap.get(materialQualityDto.getJudgmentGrade()));
        }
        return list;
    }

}
